package com.hkts.beltweigher.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.hkts.beltweigher.salve.mapper",sqlSessionFactoryRef = "salveSqlSessionFactory")
public class SQLServerConfig {
    static final String MAPPER_LOCATION = "classpath:/mapper/salve/*.xml";
    @Bean("salveDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.salve")
    public DataSource getSalveDataSource(){
        return DataSourceBuilder.create().build();
    }
    @Bean("salveSqlSessionFactory")
    public SqlSessionFactory salveSqlSessionFactory(@Qualifier("salveDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        PaginationInterceptor interceptor = new PaginationInterceptor();
        interceptor.setDbType(DbType.MYSQL);
        bean.setPlugins(interceptor);
        return bean.getObject();
    }
    @Bean("salveSqlSessionTemplate")
    public SqlSessionTemplate salveSqlSessionTemplate(@Qualifier("salveSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    @Bean("salveTransactionManager")
    public PlatformTransactionManager salveTransactionManager(@Qualifier("salveDataSource")DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
